To allow Class to inform View that its Properties have changed and that View should be redrawn we have to use
● ObservableObject Protocol that must be implemented by the Class
● @Published wrapper around each Property that should trigger View to redraw
● @ObservedObject wrapper around Class Instance inside the View (so that View takes notice of changes)
Now whenever Class Instance Property changes it will update all parts of the existing View and the other View.
SwiftUI replaced
● ObservableObject was previously BindableObject
● @ObservedObject was previously @ObjectBinding
● objectWillChange was previously willChange
ContentView.swift
import SwiftUI
//==========================================================================
// Class: User
//==========================================================================
class User : ObservableObject {
@Published var userName : String
@Published var password : String
@Published var emailAddress : String
init(userName: String, password: String, emailAddress: String) {
self.userName = userName
self.password = password
self.emailAddress = emailAddress
}
}
//==========================================================================
// ContentView
//==========================================================================
struct ContentView : View {
var newUser = User(userName: "John", password: "mypassword", emailAddress: "john@gmail.com")
var body : some View {
HStack(spacing: 20) {
LoginView1(user: newUser).border(Color.red , width: 3)
LoginView2(user: newUser).border(Color.blue, width: 3)
}
}
}
//==========================================================================
// LoginView1
//==========================================================================
struct LoginView1 : View {
@ObservedObject var user : User
var body : some View {
VStack {
TextField("Enter Username" , text: $user.userName ).padding()
TextField("Enter Password" , text: $user.password ).padding()
TextField("Enter Email Address", text: $user.emailAddress).padding()
}
}